﻿#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
#include <QUuid>

#include "MqttCommon.h"
#include "MqttWrapper.h"

#include "common/SingletonClass.h"

#define SERVER_MQTT_SIGN "fwc_server"
#define SERVER_MQTT_NAME "admin"
#define SERVER_MQTT_PASS "Aa123321"
#define SERVER_IP ""
#define SERVER_MQTT_PORT 0

MqttServer::MqttServer(QObject *parent):QObject(parent)
{

}

void MqttServer::init()
{
    m_mqtt = new MqttWrapper(SERVER_MQTT_SIGN,true);
    m_mqtt->setAddress(SERVER_IP,SERVER_MQTT_PORT);
    m_mqtt->username_pw_set(SERVER_MQTT_NAME,SERVER_MQTT_PASS);

    QObject::connect(m_mqtt,&MqttWrapper::connected,this,&MqttServer::onConnected);
    QObject::connect(m_mqtt,&MqttWrapper::disconnected,this,&MqttServer::onDisConnected);
    QObject::connect(m_mqtt,&MqttWrapper::error,this,&MqttServer::onError);
    QObject::connect(m_mqtt,&MqttWrapper::textMessageReceived,this,&MqttServer::recvMsg);

    m_mqtt->start();
}

void MqttServer::onConnected()
{
    qDebug() << "server connected ok";
    sub();
    /* 有些是不开启的，需要重新编译mosquitto添加WITH_SYS_TREE:=yes选项来指定  */
    //        m_mqtt->subscribe(nullptr,"$SYS/broker/clients/disconnected");
    //        m_mqtt->subscribe(nullptr,"$SYS/broker/bytes/received");
    //        m_mqtt->subscribe(nullptr,"$SYS/broker/clients/connected");
    //        m_mqtt->subscribe(nullptr,"$SYS/broker/#");
    //    m_mqtt->subscribe(nullptr,"#");

    //    m_mqtt->will_set(MQTT_TOPIC_status$will);
}

void MqttServer::onDisConnected()
{
    qDebug() << "server disconnect try reconnect";
    m_mqtt->reconnect();
}

void MqttServer::onError()
{
    qDebug() << "error";
}
